package com.pri.chat.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.VideoView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.netease.nim.uikit.net.SharedHelper;
import com.netease.nim.uikit.net.entity.BaseBean;
import com.netease.nim.uikit.net.entity.DTBean;
import com.netease.nim.uikit.net.entity.MessageBean;
import com.netease.nim.uikit.net.rxjava.HttpMethods;
import com.netease.nim.uikit.net.subscribers.ProgressSubscriber;
import com.netease.nim.uikit.net.subscribers.SubscriberOnNextListener;
import com.pri.chat.MainActivity;
import com.pri.chat.R;
import com.pri.chat.activity.vedio.DetailAdapter;
import com.pri.chat.activity.vedio.DetailLayoutManager;
import com.pri.chat.activity.vedio.RefreshItemEvent;
import com.pri.chat.activity.vedio.widget.DoubleLikeView;
import com.pri.chat.activity.vedio.widget.FullWindowVideoView;
import com.pri.chat.activity.vedio.widget.LikeView;
import com.pri.chat.activity.vedio.widget.NetWorkUtil;
import com.pri.chat.activity.vedio.widget.ProgressView;
import com.pri.chat.adapter.DialogCommentAdapter;
import com.pri.chat.base.BaseActivity;
import com.pri.chat.dialog.DialogUtil;
import com.pri.chat.model.DTModel;
import com.pri.chat.model.EvaListModel;
import com.pri.chat.model.GzModel;
import com.pri.chat.model.MessageModel;
import com.pri.chat.model.ZanModel;
import com.pri.chat.utils.Des3Util;
import com.pri.chat.utils.fileutils.OkManager;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.view.RxToast;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.OrientationHelper;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by weioule
 * on 2019/8/4.
 */
public class MyVedioActivity1 extends BaseActivity implements Handler.Callback, DetailAdapter.RemoveItemListener {
    private final int START_PROGRESS_ANIMATION = 8080;

    @BindView(R.id.rec_main)
    RecyclerView mRecyclerView;
    @BindView(R.id.srl_all)
    SmartRefreshLayout refreshView;
    private DetailLayoutManager myLayoutManager;

    private Handler mHandler;
    //最后播放的一条视频的数据
    private int currentPlaying = -1;
    private int mCurrentPage = 1;
    private int isPrepared;
    private boolean doubleClickWindow;
    private boolean preloading, notPreload;
    private boolean hasVideoUri, isBuffer;
    private String otherMemberId;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        //透明导航栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_vedio_detail;
    }

    @Override
    public boolean handleMessage(Message msg) {
        if (null != msg && START_PROGRESS_ANIMATION == msg.what) {
            if (null == videoView) return false;

            if (!error && null != progress)
                progress.startAnimation();

        }
        return true;
    }

    @Override
    protected void initView() {
        mList = new ArrayList<>();
        currentPlaying = getIntent().getExtras().getInt("position", 0);
        mList = (List<DTBean>) getIntent().getExtras().getSerializable("list");
        mCurrentPage = getIntent().getExtras().getInt("page",1);
        currentPlaying = getIntent().getExtras().getInt("position",0);
        otherMemberId = getIntent().getExtras().getString("id");

        refreshView.setEnableLoadmore(true);

        mHandler = new Handler(this);
        refreshView.setEnableScrollContentWhenLoaded(false);
        myLayoutManager = new DetailLayoutManager(this, OrientationHelper.VERTICAL, false);
        mRecyclerView.setLayoutManager(myLayoutManager);


        mAdapter = new DetailAdapter(R.layout.detail_item, mList);
        mAdapter.setRemoveItemListener(this);
        mRecyclerView.setAdapter(mAdapter);
        initSrl();
        initCommentDialog();
        cacheDown(mList.get(currentPlaying).getVideoPath());
    }


    private List<DTBean> mList;
    private DetailAdapter mAdapter;

    @Override
    protected void initData() {
        mRecyclerView.scrollToPosition(currentPlaying);
        myLayoutManager.setOnSelect(true);
    }

    private void cacheDown(String path){
        String finishPath = pathDirs + path.substring(path.lastIndexOf("/") + 1).replace("mp4","");
        File pFile = new File(finishPath);
        if (!pFile.exists()) {
            OkManager.getInstance().downLoadFile(path,null,null);
        }
    }


    private void loadData(){
        SubscriberOnNextListener<BaseBean<List<DTBean>>> onNextListener = baseBean -> {
            if (baseBean.getData().isEmpty() && mCurrentPage == 1) {
                mAdapter.notifyDataSetChanged();
                RxToast.normal(getString(R.string.no_data));
                notPreload = true;
            } else {
                preloading = false;
                int oldSize = mList.size();
                mList.addAll(baseBean.getData());
                mAdapter.notifyItemRangeChanged(oldSize, baseBean.getData().size());
                if(baseBean.getData().size() < 10){
                    refreshView.setEnableLoadmore(false);
                }
            }
        };
        String lat = SharedHelper.readValueByKeyForString(this, "lat");
        String lng = SharedHelper.readValueByKeyForString(this, "lng");
        DTModel dtModel = new DTModel(mCurrentPage, 1, SharedHelper.readId(this), lat, lng,"","");//登录上传参数
        dtModel.setSendMemberId(otherMemberId);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(dtModel));
        HttpMethods.getInstance().dt_list(new ProgressSubscriber<>(onNextListener, this, false), requestBody);
    }

    private void initSrl() {
        refreshView.setOnRefreshListener(refresh_layout -> {
            refresh_layout.finishRefresh(1000);
            refreshView.setEnableLoadmore(true);
            mCurrentPage = 1;
            notPreload = false;
            loadData();
        });
        refreshView.setOnLoadmoreListener(refresh_layout -> {
            refresh_layout.finishLoadmore(1000);
            if (!preloading) {
                preloading = true;
                mCurrentPage++;
                loadData();
            }
        });

        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int position = myLayoutManager.findLastVisibleItemPosition();
                //上拉预加载
                if (!preloading && !notPreload && (mList.size() > 1 && mList.size() - position < 3)) {
                    if (!preloading) {
                        preloading = true;
                        mCurrentPage++;
                        loadData();
                    }
                }
            }
        });

        myLayoutManager.setOnViewPagerListener(new DetailLayoutManager.OnViewPagerListener() {
            @Override
            public void onPageRelease(boolean isNext, final int position) {
                mHandler.removeMessages(START_PROGRESS_ANIMATION);
                int index;
                if (isNext) {
                    index = 0;
                } else {
                    index = 1;
                }
                releaseVideo(index);
            }

            @Override
            public void onPageSelected(int position, boolean isNext) {
                if(mList.get(position).getStatus() == -1){
                    showToams("服务器正在处理该视频，暂时无法播放！");
                }else{
                    playVideo(position);
                }
            }
        });
    }


    @Override
    public void removeItem(int position) {
        mList.remove(position);
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                mAdapter.notifyItemChanged(position);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (currentPlaying >= 0) {
            playVideo(currentPlaying);
        }
    }


    private ImageView imgPlay;
    private ImageView img_thumb;
    private FullWindowVideoView videoView;
    private ProgressView progress;
    private ImageView shareImg;
    private TextView gzTv;

    private void playVideo(int position) {
        if (currentPlaying == position && null != videoView && videoView.isPlaying()) return;
        currentPlaying = position;
        BaseViewHolder holder = (BaseViewHolder) mRecyclerView.findViewHolderForLayoutPosition(position);
        if (null == holder || null == holder.itemView) return;
        videoView = holder.getView(R.id.video_view);
        shareImg = holder.getView(R.id.shareImg);
        gzTv = holder.getView(R.id.gzTv);
        if (null == videoView) return;
        videoView.requestFocus();

        imgPlay = holder.getView(R.id.img_play);
        img_thumb = holder.getView(R.id.img_thumb);
        progress = holder.getView(R.id.progress);
        img_thumb.animate().alpha(1).start();
        doPlay();
        setListener(holder);

        if(currentPlaying>0){
            cacheDown(mList.get(currentPlaying-1).getVideoPath());
        }
        if(currentPlaying+1<mList.size()){
            cacheDown(mList.get(currentPlaying+1).getVideoPath());
        }
        if(currentPlaying+2<mList.size()){
            cacheDown(mList.get(currentPlaying+2).getVideoPath());
        }
        if(currentPlaying+3<mList.size()){
            cacheDown(mList.get(currentPlaying+3).getVideoPath());
        }
    }

    private boolean error;

    private void doPlay() {
        error = false;
        hasVideoUri = false;

        //在无线网下自己播放
        if (NetWorkUtil.getAPNType(this) == ConnectivityManager.TYPE_WIFI) {
            startVideoPlay();
//        } else if (0 == NetWorkUtil.getAPNType(this)) {
//            imgPlay.animate().alpha(01f).scaleX(0.4f).scaleY(0.4f).start();
//            RxToast.showToast("当前无网络可用,请检查网络!");
        } else {
            startVideoPlay();
        }
    }


    private String pathDirs = Environment.getExternalStorageDirectory()+"/com.pri.chat/cache/video/";
    private void startVideoPlay() {
        if (null == videoView) return;
        isPrepared = -1;
        imgPlay.animate().alpha(0f).scaleX(1f).scaleY(1f).start();
        String path = (String)videoView.getTag();
        String finishPath = pathDirs + path.substring(path.lastIndexOf("/") + 1).replace("mp4","");
        File pFile = new File(finishPath);
        if(pFile.exists()){
            //存在
            videoView.setVideoURI(Uri.parse(finishPath));
        }else{
            videoView.setVideoURI(Uri.parse(path));
        }
        videoView.start();
        hasVideoUri = true;

        //延迟一秒开启加载动画
        Message message = Message.obtain();
        message.what = START_PROGRESS_ANIMATION;
        mHandler.sendMessageDelayed(message, 1000);

        videoView.setOnInfoListener(new MediaPlayer.OnInfoListener() {
            @Override
            public boolean onInfo(MediaPlayer mp, int what, int extra) {
                img_thumb.animate().alpha(0).setDuration(200).start();
                isPrepared = 1;
                if (what == MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START) {
                    //如果没在播放，则手动播放
                    if (!videoView.isPlaying()) {
                        mp.seekTo(videoView.getCurrentPosition());
                        mp.start();
                    }

                    if (videoView.isPlaying()) {
                        //播放后移除加载动画任务
                        mHandler.removeMessages(START_PROGRESS_ANIMATION);
                        progress.cancelAnimation();
                        progress.setProgress(0, videoView);
                        error = false;
                        isBuffer = false;

                        //观看次数++
//                        int plNum = Integer.parseInt(mList.get(currentPlaying).getPlNum());
//                        mList.get(currentPlaying).setPlNum((plNum + 1) + "");

                        EventBus.getDefault().post(new RefreshItemEvent(currentPlaying, 1));
                    }

                } else if (what == MediaPlayer.MEDIA_INFO_BUFFERING_START) {
                    //缓冲中
                    isBuffer = true;
                    progress.end();
                    progress.startAnimation();

                } else if (what == MediaPlayer.MEDIA_INFO_BUFFERING_END) {
                    //恢复播放
                    isBuffer = false;
                    progress.setProgress(videoView.getCurrentPosition(), videoView);
                }
                return false;
            }
        });

        videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer arg0) {
                if (null == arg0 || arg0.isPlaying()) return;
                if (!error) {
                    videoView.seekTo(0);
                    videoView.start();
                    progress.setProgress(0, videoView);
                }
            }
        });

        videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                progress.cancelAnimation();

                error = true;
                imgPlay.animate().alpha(01f).scaleX(0.4f).scaleY(0.4f).start();
                if (0 == NetWorkUtil.getAPNType(MyVedioActivity1.this)) {
                    RxToast.showToast("当前无网络可用,请检查网络!");
                }
                return false;
            }
        });
    }

    private GestureDetector mDetector;
    private long lastDubleTime;
    DoubleLikeView like;
    LikeView likeView;
    TextView give_a_like_num;
    TextView pl_num;
    ImageView plImage;
    private void setListener(BaseViewHolder holder) {
        like = holder.getView(R.id.like);
        likeView = holder.getView(R.id.lv_icon);
        give_a_like_num = holder.getView(R.id.give_a_like_num);
        pl_num = holder.getView(R.id.pl_num);
        plImage = holder.getView(R.id.plImage);

        mDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onDown(MotionEvent e) {
                return true;
            }

            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                return false;
            }

            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                //连续双击最后的单数，google的GestureDetector把它归类为单击，我认为不应该归类为单击的，在这里将它归属于双击
                if (System.currentTimeMillis() - lastDubleTime <= 600) {
                    onDoubleTap(e);
                    return false;
                }

                lastDubleTime = 0;

                //正在加载中则不响应、缓冲中不响应
                if (null == videoView || isPrepared < 0 && !error || (isBuffer && videoView.isPlaying())) {
                    return false;
                }

                if (videoView.isPlaying() && !isBuffer) {
                    imgPlay.animate().alpha(01f).scaleX(0.4f).scaleY(0.4f).start();
                    videoView.pause();
                    progress.pause();
                } else {
                    //之前没网络或是4G网络，没进入播放流程，没设置过uri，则进入播放逻辑
                    if (!hasVideoUri) {
                        doPlay();
                        return false;
                    }

                    if (0 == NetWorkUtil.getAPNType(MyVedioActivity1.this)) {
                        RxToast.showToast("当前无网络可用,请检查网络!");
                        return false;
                    }

                    imgPlay.animate().alpha(0f).scaleX(1f).scaleY(1f).start();
                    videoView.start();
                    if (error) {
                        //之前播放失败，则重新展示加载动画
                        progress.startAnimation();
                    } else {
                        //正常情况下，就是点击继续播放
                        progress.resume();
                    }
                }
                return true;
            }

            @Override
            public boolean onDoubleTap(MotionEvent e) {
                lastDubleTime = System.currentTimeMillis();
                doubleClickWindow = true;
                like.startAnimator(e);
                likeView.performClick();
                return true;
            }
        });

        like.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return mDetector.onTouchEvent(event);
            }
        });

        likeView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DTBean dtObj = mList.get(currentPlaying);

                //双击只能点赞，不能取消点赞
                if ((doubleClickWindow && likeView.isChecked()) || (doubleClickWindow && dtObj.getSfdz() == 1) && !likeView.isChecked()) {
                    doubleClickWindow = false;
                    return;
                }

                doubleClickWindow = false;

                httpLike(currentPlaying);
            }
        });

        plImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                refreshCommentList(true);
            }
        });

        shareImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initShareDialog(mList.get(currentPlaying).getVideoPath() + "?vframe/jpg/offset/1", currentPlaying);
            }
        });
        gzTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //关注方法
                httpGz();
            }
        });
    }

    private void httpGz() {
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            if(baseBean.isSuccess()){
                if(mList.get(currentPlaying).getSfgz() == 0){
                    RxToast.normal("关注成功！");
                    mList.get(currentPlaying).setSfgz(1);
                    gzTv.setText("已关注");
                    gzTv.setBackgroundResource(R.drawable.btn_gray_20_shape);
                    gzTv.setVisibility(View.GONE);
                }else{
                    RxToast.normal("取消关注成功！");
                    mList.get(currentPlaying).setSfgz(0);
                    gzTv.setText("关注");
                    gzTv.setBackgroundResource(R.drawable.btn_orange_shape);
                    gzTv.setVisibility(View.VISIBLE);
                }
                for(int i=0;i<mList.size();i++){
                    if(i != currentPlaying){
                        if(mList.get(i).getMemberId().equals(mList.get(currentPlaying).getMemberId())){
                            mList.get(i).setSfgz(mList.get(currentPlaying).getSfgz());
                        }
                    }
                }
                sendBroadcastToMain(0);
            }
        };
        GzModel userModel = new GzModel();
        userModel.setGzrId(SharedHelper.readId(this));
        userModel.setBgzId(mList.get(currentPlaying).getMemberId());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(userModel));
        HttpMethods.getInstance().saveGuanZhu(new ProgressSubscriber<>(onNextListener, this, true), requestBody);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (null != videoView) videoView.pause();
        if (null != progress) progress.cancel();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != videoView)
            videoView.stopPlayback();
        mHandler.removeCallbacksAndMessages(null);

        EventBus.getDefault().post(new RefreshItemEvent(currentPlaying, 2));
    }


    private void releaseVideo(int index) {
        View itemView = mRecyclerView.getChildAt(index);
        if (null == itemView) return;

        final VideoView videoView = itemView.findViewById(R.id.video_view);
        if (null == videoView) return;
        ImageView imgPlay = itemView.findViewById(R.id.img_play);
        ProgressView progress = itemView.findViewById(R.id.progress);
        videoView.stopPlayback();
        progress.cancel();
        imgPlay.animate().alpha(0f).start();
    }

    private void httpLike(int pos) {
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            if(baseBean.isSuccess()){
                //之前就已经点过赞的，再点就取消
                if (mList.get(pos).getSfdz() == 1 && !likeView.isChecked()) {
                    likeView.setChecked(false);
                    likeView.setDefaultIcon(getResources().getDrawable(R.drawable.not_thumb_up));
                } else {
                    likeView.toggle();
                }

                mList.get(pos).setSfdz(mList.get(pos).getSfdz() == 1 ? 0 : 1);
                int zanNum = mList.get(pos).getZanNum();
                if (likeView.isChecked()) {
                    mList.get(pos).setZanNum(zanNum + 1);
                } else {
                    mList.get(pos).setZanNum(zanNum - 1);
                }

                give_a_like_num.setText(mList.get(pos).getZanNum() + "");
                EventBus.getDefault().post(new RefreshItemEvent(currentPlaying, 1));
                sendBroadcastToMain(0);
            }
        };
        ZanModel zanModel = new ZanModel();
        zanModel.setBdzId(mList.get(pos).getId());
        zanModel.setDzrId(SharedHelper.readId(mContext));
        zanModel.setType(1);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(zanModel));
        HttpMethods.getInstance().saveDianZan(new ProgressSubscriber<>(onNextListener, mContext, true), requestBody);
    }


    private int comment_page = 1;
    private List<MessageBean> mCommentList = new ArrayList<>();
    private DialogCommentAdapter mCommentAdapter;
    private void refreshCommentList(boolean s) {
        comment_page = 1;
        mCommentList.clear();
        mCommentAdapter.notifyDataSetChanged();
        httpGetComment(s);
    }

    private void httpGetComment(boolean isShowComment) {
        SubscriberOnNextListener<BaseBean<List<MessageBean>>> onNextListener = baseBean -> {
            if (isShowComment) {
                mCommentDialog.show();
            }
            if (baseBean.getData().isEmpty() && comment_page == 1) {
                mIvNone.setVisibility(View.VISIBLE);
                mCommentAdapter.notifyDataSetChanged();

            } else {
                mIvNone.setVisibility(View.INVISIBLE);
                mCommentList.addAll(baseBean.getData());
                mCommentAdapter.notifyDataSetChanged();
            }
        };

        EvaListModel evaListModel = new EvaListModel();
        evaListModel.setPageIndex(comment_page);
        evaListModel.setObjId(mList.get(currentPlaying).getId());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(evaListModel));
        HttpMethods.getInstance().listPingLun(new ProgressSubscriber<>(onNextListener, mContext, false), requestBody);
    }

    private void httpSendMessage() {
        HideSoftInput(ll_huifu.getWindowToken());
        SubscriberOnNextListener<BaseBean<List<MessageBean>>> onNextListener = baseBean -> {
            RxToast.normal("评论成功");
            mEtInput.setText("");
            int plNum = Integer.parseInt(mList.get(currentPlaying).getPlNum());
            mList.get(currentPlaying).setPlNum((plNum + 1) + "");
            pl_num.setText(mList.get(currentPlaying).getPlNum());
            refreshCommentList(false);
            sendBroadcastToMain(0);
        };
        Gson gson = new Gson();
        MessageModel circleEnity = new MessageModel();
        circleEnity.setType(1);
        circleEnity.setObjId(mList.get(currentPlaying).getId());
        circleEnity.setMemberId(SharedHelper.readId(mContext));
        circleEnity.setContent(mEtInput.getText().toString());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(circleEnity));
        HttpMethods.getInstance().savePingLun(new ProgressSubscriber<>(onNextListener, mContext, false), requestBody);
    }

    // 隐藏软键盘
    private void HideSoftInput(IBinder token) {
        if (token != null) {
            InputMethodManager manager = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
            manager.hideSoftInputFromWindow(token,
                    InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    Dialog mCommentDialog;
    private SmartRefreshLayout mSrlComment;
    private EditText mEtInput;
    private TextView mTvSendMessage;
    private RecyclerView mRvComment;
    private ImageView mIvClose, mIvNone;
    private LinearLayout ll_huifu;
    private void initCommentDialog() {
        mCommentDialog = new Dialog(mContext, R.style.Theme_Light_Dialog);
        View dialogView = LayoutInflater.from(mContext).inflate(R.layout.dialog_comment, null);
        mSrlComment = dialogView.findViewById(R.id.srl_comment);
        mRvComment = dialogView.findViewById(R.id.rec_comment);
        mIvClose = dialogView.findViewById(R.id.iv_close);
        mIvNone = dialogView.findViewById(R.id.iv_none);
        mTvSendMessage = dialogView.findViewById(R.id.tv_send_message);
        mEtInput = dialogView.findViewById(R.id.et_input);
        ll_huifu = dialogView.findViewById(R.id.ll_huifu);
        ll_huifu.setVisibility(View.VISIBLE);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        mRvComment.setLayoutManager(linearLayoutManager);
        mRvComment.setNestedScrollingEnabled(false);
        mCommentAdapter = new DialogCommentAdapter(R.layout.item_message, mCommentList);
        mRvComment.setAdapter(mCommentAdapter);
        //获得dialog的window窗口
        Window window = mCommentDialog.getWindow();
        WindowManager wm = getWindowManager();
        //设置dialog在屏幕底部
        window.setGravity(Gravity.BOTTOM);
        //设置dialog弹出时的动画效果，从屏幕底部向上弹出

        window.setWindowAnimations(R.style.dialogStyle);
        window.getDecorView().setPadding(0, 0, 0, 0);
        //获得window窗口的属性
        WindowManager.LayoutParams lp = window.getAttributes();
        //设置窗口宽度为充满全屏
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        //设置窗口高度为包裹内容
        lp.height = 1200;
        //将设置好的属性set回去
        window.setAttributes(lp);
        //将自定义布局加载到dialog上
        mCommentDialog.setContentView(dialogView);

        initListener();
        mCommentAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.iv_logo:
                        if (mCommentList.get(position).getMemberId().equals(SharedHelper.readId(mContext))) {
                            RxActivityTool.skipActivity(mContext, PeopleMsgActivity.class);
                        } else {
                            Bundle bundle = new Bundle();
                            bundle.putString("id", mCommentList.get(position).getMemberId());
                            RxActivityTool.skipActivity(mContext, OtherPeopleMsgActivity.class, bundle);
                        }
                        break;
                }
            }
        });
    }

    private void initListener() {
        mSrlComment.setOnRefreshListener(refreshlayout -> {
            refreshlayout.finishRefresh(1500);
            refreshCommentList(false);
        });
        mSrlComment.setOnLoadmoreListener(refreshlayout -> {
            refreshlayout.finishLoadmore(1500);
            comment_page++;
            httpGetComment(false);
        });
        mTvSendMessage.setOnClickListener(view -> {
            if (mEtInput.getText().toString().isEmpty()) {
                RxToast.normal(mEtInput.getHint().toString());
                return;
            }
            httpSendMessage();
        });
        mIvClose.setOnClickListener(view -> {
            mCommentDialog.dismiss();
        });

    }

    private Dialog mShareDialog;
    private void initShareDialog(String path, int pos) {
        String memberId = SharedHelper.readId(mContext);
        String listMemberId = mList.get(pos).getMemberId();
        int type = 1;
        if (listMemberId.equals(memberId)) {
            type = 2;
        }
        mShareDialog = DialogUtil.getInstance().showShareDialog(activity, type);
        DialogUtil.getInstance().setOnShareClickListener(new DialogUtil.OnShareClickListener() {
            @Override
            public void qqOnClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("id",mList.get(pos).getId());
                bundle.putString("image",path);
                bundle.putString("title",mList.get(pos).getMemberName());
                bundle.putString("content",mList.get(pos).getContent());
                bundle.putInt("type",2);
                RxActivityTool.skipActivity(mContext, ShareMemberActivity.class,bundle);
                mShareDialog.dismiss();
            }

            @Override
            public void circleOnClick(View v) {
                mShareDialog.dismiss();
                DialogUtil.getInstance().shareWechatMoments(path,HttpMethods.SHARE_TITLE,mList.get(pos).getContent(),HttpMethods.SHARE_URL);
            }

            @Override
            public void qZoneOnClick(View v) {
                mShareDialog.dismiss();
                //删除操作
                deleteDongTai();
            }

            @Override
            public void weixinOnClick(View v) {
                mShareDialog.dismiss();
                DialogUtil.getInstance().shareWeChat(path,HttpMethods.SHARE_TITLE,mList.get(pos).getContent(),HttpMethods.SHARE_URL);
            }

            @Override
            public void jubaoOnClick(View v) {
                mShareDialog.dismiss();

                Bundle bundle = new Bundle();
                bundle.putString("id",mList.get(currentPlaying).getId());
                bundle.putString("type","1");
                RxActivityTool.skipActivity(mContext, ReleaseJuBaoAcctivity.class,bundle);
            }
        });
        mShareDialog.show();
    }

    private void deleteDongTai() {
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            if (baseBean.isSuccess()) {
                RxToast.normal("删除成功！");
                if(mList.size()>1){
                    if(currentPlaying ==1) {
                        mList.remove(currentPlaying);
                        mAdapter.notifyDataSetChanged();
                        currentPlaying = 1;
                    }else if(currentPlaying == mList.size()-1) {
                        mList.remove(currentPlaying);
                        mAdapter.notifyDataSetChanged();
                        currentPlaying = mList.size()-1;
                    }else {
                        mList.remove(currentPlaying);
                        mAdapter.notifyDataSetChanged();
                        currentPlaying = currentPlaying;
                    }
                    mRecyclerView.scrollToPosition(currentPlaying);
                    myLayoutManager.setOnSelect(true);
                }
                sendBroadcastToMain(1);
            }
        };

        Map<String, Object> params = new HashMap<>();
        params.put("id", mList.get(currentPlaying).getId());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(params));
        HttpMethods.getInstance().deleteDongTai(new ProgressSubscriber<>(onNextListener, mContext, false), requestBody);
    }

    public void sendBroadcastToMain(int type) {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        if (type == 0) {
            intent.setAction(MainActivity.UPDATE_VEDIO);
        }else if(type == 1){
            intent.setAction(MainActivity.DELETE_VEDIO);
        }
        bundle.putParcelable("dtObj", mList.get(currentPlaying));
        intent.putExtras(bundle);
        sendBroadcast(intent);
    }
}
